package entity

import (
	"errors"
	"fmt"
	"net/http"
	"os"

	"github.com/jinzhu/gorm"
	"github.com/labstack/echo"
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/workflow"
	"shqsoft.cn/pasnj/workflow/entity"
)

//COMP_JC 附件
type COMP_JC struct {
	ID          int    `gorm:"column:ID;AUTO_INCREMENT;primary_key" json:"ID"`
	UTID        int    `gorm:"column:UTID"`
	FID         int    `gorm:"column:FID"`
	FZRID       int    `gorm:"column:FZRID"`
	EMID1       int    `gorm:"column:EMID1"`
	EMID2       int    `gorm:"column:EMID2"`
	EMID3       int    `gorm:"column:EMID3"`
	JCRW        string `gorm:"column:JCRW"`
	SSTX        string `gorm:"column:SSTX"`
	SSTXCaption string `gorm:"-"`
	CNRQ        string `gorm:"column:CNRQ"`
	JYDW        string `gorm:"column:JYDW"`
	FZRNO       string `gorm:"column:FZRNO"`
	FZR         string `gorm:"column:FZR"`
	EMNO1       string `gorm:"column:EMNO1"`
	EMNO2       string `gorm:"column:EMNO2"`
	EMNO3       string `gorm:"column:EMNO3"`
	KHJL1       string `gorm:"column:KHJL1"`
	KHJL2       string `gorm:"column:KHJL2"`
	KHJL3       string `gorm:"column:KHJL3"`
	BZ          string `gorm:"column:BZ"`
	BZ2         string `gorm:"column:BZ2"`
	FRID        int    `gorm:"column:FRID"`
	UID         int    `gorm:"column:UID"`

	STEP     int     `gorm:"-" json:"step"`
	Progress float64 `gorm:"-" json:"progress"`
	StepName string  `gorm:"-" json:"stepName"`
	Status   string  `gorm:"-" json:"status"`
}

//TableName COMP_JC表名
func (COMP_JC) TableName() string {
	return "T_COMP_JC"
}

//BeforeSave 保存前的触发器
func (i *COMP_JC) BeforeSave(tx *gorm.DB) (err error) {
	if i.FID == 0 {
		return errors.New("未上传附件或上传附件不正确，请删除后重新上传")
	}
	sqlEx := "select ID,SysUserName from T_SysUser where SysUserID=?"
	row := tx.Raw(sqlEx, i.EMNO1).Row()
	row.Scan(&i.EMID1, &i.KHJL1)
	if i.EMNO2 != "" {
		sqlEx := "select ID,SysUserName from T_SysUser where SysUserID=?"
		row := tx.Raw(sqlEx, i.EMNO2).Row()
		row.Scan(&i.EMID2, &i.KHJL2)
	}
	if i.EMNO3 != "" {
		sqlEx := "select ID,SysUserName from T_SysUser where SysUserID=?"
		row := tx.Raw(sqlEx, i.EMNO3).Row()
		row.Scan(&i.EMID3, &i.KHJL3)
	}

	sqlEx = "select ID,SysUserName from T_SysUser where SysUserID=?"
	row = tx.Raw(sqlEx, i.FZRNO).Row()
	row.Scan(&i.FZRID, &i.FZR)

	sqlEx = "select ID from T_Organization where OrganName=?"
	row = tx.Raw(sqlEx, i.JYDW).Row()
	row.Scan(&i.UTID)

	wfid := 7
	if i.SSTX == "2" {
		wfid = 8
	}
	if i.SSTX == "3" {
		wfid = 9
	}
	runid, err := workflow.Create(wfid, i.UID, tx)
	if err != nil {
		return err
	}
	i.FRID = runid

	return
}

// AfterFind 查询后触发器
func (i *COMP_JC) AfterFind(tx *gorm.DB) (err error) {
	if i.SSTX == "1" {
		i.SSTXCaption = "公司银行线"
	} else if i.SSTX == "2" {
		i.SSTXCaption = "同业票据线"
	} else {
		i.SSTXCaption = "交易银行线"
	}
	if i.FRID == 0 {
		i.Status = "exception"
		i.StepName = "校验错误"
		return
	}
	run := entity.FlowRun{}
	if err = tx.Find(&run, i.FRID).Error; err != nil {
		tx.Rollback()
		return
	}
	wf := workflow.GetWorkFlow(run.WFID)
	if wf == nil {
		return fmt.Errorf("指定的流程ID:%d在流程配置中不存在！", run.WFID)
	}
	act := wf.GetAction(run.Step)
	if act == nil {
		return fmt.Errorf("指定的stepID:%d在流程%s配置中不存在！", run.Step, wf.Name)
	}
	count := len(wf.Actions)
	i.STEP = run.Step
	i.StepName = "审批中"
	if i.STEP == 1 {
		i.StepName = "申请中"
	}
	i.Progress = float64(act.Step*100) / float64(count)
	if i.Progress >= 100 && run.State == "0" {
		i.Progress = 95
	}
	i.Status = ""
	if run.State == "0" {
		i.Status = "active"
	} else if run.State == "2" {
		i.StepName = "已中止"
		i.Status = "exception"
	} else {
		i.StepName = "已完成"
		i.Status = "success"
	}
	return
}

func (i *COMP_JC) AfterDelete(tx *gorm.DB) (err error) {
	//删除所有附件
	if i.FID > 0 {
		var fj BaseFJ
		err = base.DB.First(&fj, i.FID).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		fileName := fj.FJMC + "." + fj.FJLX

		path, err := base.WorkDir()
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		filePath := path + "/upload_file/doc/" + fileName

		err = os.Remove(filePath)
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		err = base.DB.Where([]int{i.FID}).Delete(BaseFJ{}).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
	}
	//删除监测项目
	err = base.DB.Where("RWID = ?", i.ID).Delete(COMP_JC_MX{}).Error
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	//删除流程信息
	if i.FRID > 0 {
		return workflow.DeleteWithTx(i.FRID, tx)
	}
	return nil
}

//FilesEF 获取实体类对象"EmplYgdd";
func COMP_JCEF() base.EntityFunc {
	return func() interface{} {
		entity := COMP_JC{}
		return &entity
	}
}

//COMP_JCESF 获取实体类对象数组
func COMP_JCESF() base.EntitiesFunc {
	return func() interface{} {
		var entities []COMP_JC
		return &entities
	}
}
func init() {
	dao := base.NewDefaultDao(COMP_JCEF(), COMP_JCESF(), nil)
	filter := base.WorkFolowFilter{
		FilterColName: "FRID",
	}
	filter.SetAdditional("wfid", "7,8,9")
	dao.Fileter = &filter
	base.DaoPoolObj.Put("COMP_JC", dao)
}
